import { computed, defineComponent, onMounted, ref, watch } from "vue";
import tinyMceEditor from "@tinymce/tinymce-vue";
import "public/resource/tinymce/tinymce.min";
import "public/resource/tinymce/tinymce.d";
import "public/resource/tinymce/models/dom/model.min"

import configDefault from "./default-config";
import axios from "@/axios";

declare global {
    interface Window {
        tinymce: any;
    }
}

export default defineComponent({
    name: "Editor",
    components: { tinyMceEditor },
    props: {
        value: {
            type: String,
            default: "",
        },
        disabled: {
            type: Boolean,
            default: false,
        },
        init: {
            type: Object,
            default() {
                return {};
            },
        },
    },
    emits: ["update:modelValue"],
    setup: async (props, context) => {

        const editorRef = ref()
        const eid = "id" + Date.now();

        // 双向绑定
        const val = computed({
            get() {
                if(props.value){
                    return  props.value.replace(/"##urlRoot##/g, `"${axios.getBaseURL()
                        .replace("/","")}/`);
                }
                return props.value;
            },
            set(newVal: string) {
                if(newVal){
                    newVal = newVal.replace(new RegExp(`"${axios.getBaseURL()
                        .replace("/","")}/`, 'g'),
                        "\"##urlRoot##");
                }
                console.log(newVal)
                context.emit("update:modelValue", newVal);
            },
        });

        // 配置对象
        const config = computed(() => {
            const obj = Object.assign(configDefault, props.init);

            return obj;
        });

        // 监听disabled
        watch(
            () => props.disabled,
            (val: boolean) => {
                if (window.tinymce.editors && window.tinymce.editors[eid])
                    window.tinymce.editors[eid].setMode(val ? "readonly" : "design");
            }
        );

        onMounted(() => {
            // context.emit("update:modelValue", val);
            // window.tinymce.editors[eid].setMode(val ? "readonly" : "design");
        });

        return {
            val,
            config,
            eid,
            editorRef
        }

    },
    render() {
        return (
            <tinyMceEditor ref="editorRef" v-model={this.val} init={this.config} id={this.eid} />
        )

    }
})